package com.qing.administer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qing.administer.entity.SysUser;
import com.qing.administer.mapper.SysUserMapper;
import com.qing.administer.pojo.dto.UserLoginDTO;
import com.qing.administer.result.CommonException;
import com.qing.administer.result.ResultCode;
import com.qing.administer.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author qing
 * @since 2021-09-17
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


	@Autowired
	private SysUserMapper sysUserMapper;


	/**
	 * 用户登录
	 * @param userLoginDTO
	 * @return
	 */
	public String login(UserLoginDTO userLoginDTO){
		//返回token
		String token="";

		QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("username",userLoginDTO.getName());
		List<SysUser> users=sysUserMapper.selectList(queryWrapper);

		//用户不存在
		if(CollectionUtils.isEmpty(users)){
			throw new CommonException(ResultCode.USER_NOT_EXIST);
		}


		for (SysUser user : users) {
			if(SecureUtil.md5(userLoginDTO.getPassword()).equals(user.getPassword())){
				StpUtil.login(user.getUserId());
				token=StpUtil.getTokenValue();
				break;
			}
		}

		//用户密码错误
		if(!StringUtils.hasLength(token)){
			throw new CommonException(ResultCode.USER_PASSWORD_ERROR);
		}
		return  token;
	};


	@Override
	public Page<SysUser> findPage(Long current, Long size, Integer status, String keyword) {
		Page<SysUser> page=new Page<>(current,size);
		QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
		if(StringUtils.hasLength(keyword)){
			queryWrapper.likeRight("username",keyword).or().likeRight("email",keyword);
		}
		return sysUserMapper.selectPage(page,queryWrapper);
	}
}
